﻿using System.Diagnostics;
using FwkLight.Domain.Fetching;
using FwkLight.Persistence;
using NHibernate;

namespace FwkLight.Domain.Repository
{
  public class BaseRepository<EntityType> : IBaseRepo<EntityType>
    where EntityType : class
  {
    private readonly INHUnitOfWork _unitOfWork;
    private readonly IEntityMultiCriteriaFetcher<EntityType> _multiCriteriaFetcher;

    [DebuggerNonUserCode]
    public BaseRepository ( INHUnitOfWorkProvider nhUnitOfWorkProvider )
    {
      _unitOfWork = nhUnitOfWorkProvider.GetCurrentUnitOfWork();
      _multiCriteriaFetcher = new EntityMultiCriteriaFetcher<EntityType>();
    }

    public IEntityMultiCriteriaFetcher<EntityType> MultiCriteriaFetcher
    {
      [DebuggerNonUserCodeAttribute]
      get
      {
        return _multiCriteriaFetcher;
      }
    }

    protected ISession Session
    {
      [DebuggerNonUserCodeAttribute]
      get { return _unitOfWork.Session; }
    }

    [DebuggerNonUserCodeAttribute]
    public EntityType SaveOrUpdate ( EntityType entity )
    {
      Session.SaveOrUpdate(entity);
      SaveSubEntitiesFor(entity);

      return entity;
    }

    [DebuggerNonUserCodeAttribute]
    public void Delete ( EntityType entity )
    {
      Session.Delete(entity);
    }

    [DebuggerNonUserCode]
    public EntityType LoadEntity ( )
    {
      return _multiCriteriaFetcher.LoadEntity(_unitOfWork.Session);
    }

    public EntityType LoadById ( int id )
    {
      return Session.Load<EntityType>(id);
    }

    [DebuggerNonUserCodeAttribute]
    protected virtual void SaveSubEntitiesFor ( EntityType entity )
    {
    }
  }
}